<template>
  <view class="cart-page" :style="{'--primary-color': primaryColor}">
    <!-- 页面加载状态 -->
    <PageLoading :show="pageLoading" :primary-color="primaryColor" loading-text="加载中..." />
    
    <!-- 页面主要内容 -->
    <view class="page-content" v-show="shouldShowContent">
    <!-- 顶部标题栏 -->
    <view class="cart-header">
      <text class="header-title">我的商品</text>
      <view class="header-actions">
        <text class="header-edit" @click="toggleEditMode">{{ isEditMode ? '完成' : '编辑' }}</text>
      </view>
    </view>

    <!-- 购物车为空状态 -->
    <view class="empty-cart" v-if="cartItems.length === 0">
      <view class="empty-content">
        <text class="empty-text">购物车空空如也</text>
        <text class="empty-desc">快去挑选心仪的商品吧~</text>
      </view>
      <view class="go-shopping-btn" :style="{'--primary-color': primaryColor}" @click="goShopping">
        <text class="btn-text">去逛逛</text>
      </view>
    </view>

    <!-- 购物车商品列表 -->
    <view class="cart-content" v-else>
      <view class="cart-item" v-for="(item, index) in cartItems" :key="item.id">
        <view class="item-image" @click="goToDetail(item.productId)">
          <image :src="item.image" mode="aspectFill"></image>
        </view>
        
        <view class="item-info" @click="goToDetail(item.productId)">
          <text class="item-name">{{ item.name }}</text>
          <view class="item-tags">
            <view class="tag-row" v-if="item.style">
              <text class="tag-label">款式：</text>
              <text class="tag-value">{{ item.style }}</text>
            </view>
            <view class="tag-row" v-if="item.category">
              <text class="tag-label">分类：</text>
              <text class="tag-value">{{ item.category }}</text>
            </view>
          </view>
          <view class="item-price-row">
            <text class="item-price">¥{{ item.price }}</text>
            <text class="item-original-price" v-if="item.originalPrice > item.price">¥{{ item.originalPrice }}</text>
          </view>
        </view>
        
        <view class="item-actions">
          <view class="quantity-control">
            <view class="quantity-btn" @click="decreaseQuantity(index)">
              <text class="btn-text">-</text>
            </view>
            <text class="quantity-text">{{ item.quantity }}</text>
            <view class="quantity-btn" @click="increaseQuantity(index)">
              <text class="btn-text">+</text>
            </view>
          </view>
          
          <view class="delete-btn" v-if="isEditMode" @click="deleteItem(index)">
            <text class="delete-text">删除</text>
          </view>
        </view>
        
        <view class="item-checkbox" :class="{ selected: item.selected }" @click="toggleItemSelect(index)">
          <text class="checkbox-icon">{{ item.selected ? '✓' : '' }}</text>
        </view>
      </view>
    </view>

    <!-- 底部结算栏 -->
    <view class="cart-footer" :style="{'--primary-color': primaryColor}" v-if="cartItems.length > 0">
      <view class="footer-left">
        <view class="select-all" @click="toggleSelectAll">
          <text class="checkbox-icon" :class="{ selected: isAllSelected }">{{ isAllSelected ? '✓' : '' }}</text>
          <text class="select-text">全选</text>
        </view>
        
        <view class="total-info" v-if="!isEditMode">
          <text class="total-label">合计：</text>
          <text class="total-price">¥{{ totalPrice.toFixed(2) }}</text>
          <text class="total-desc">不含运费</text>
        </view>
      </view>
      
      <view class="footer-right">
        <view class="checkout-btn" v-if="!isEditMode" @click="checkout">
          <text class="btn-text">结算({{ selectedCount }})</text>
        </view>
        
        <view class="batch-delete-btn" v-if="isEditMode" @click="batchDelete">
          <text class="btn-text">删除选中</text>
        </view>
      </view>
    </view>
    
    <!-- 确认结算弹窗 -->
    <view class="checkout-modal" v-if="showCheckoutModal" @click="closeCheckoutModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">确认结算</text>
          <view class="close-btn" @click="closeCheckoutModal">
            <text class="close-icon">×</text>
          </view>
        </view>
        
        <view class="modal-body">
          <view class="order-summary">
            <text class="summary-title">订单商品 ({{ selectedCount }}件)</text>
            <view class="goods-list">
              <view class="goods-item" v-for="item in selectedItems" :key="item.id">
                <image :src="item.image" class="goods-image" mode="aspectFill"></image>
                <view class="goods-info">
                  <text class="goods-name">{{ item.name }}</text>
                  <text class="goods-spec">{{ item.spec || '默认规格' }}</text>
                  <view class="goods-price-qty">
                    <text class="goods-price">¥{{ item.price }}</text>
                    <text class="goods-qty">×{{ item.quantity }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
          
          <view class="payment-summary">
            <view class="summary-row">
              <text class="summary-label">商品总价：</text>
              <text class="summary-value">¥{{ totalPrice.toFixed(2) }}</text>
            </view>
            <view class="summary-row">
              <text class="summary-label">运费：</text>
              <text class="summary-value">¥0.00</text>
            </view>
            <view class="summary-row total-row">
              <text class="summary-label">实付款：</text>
              <text class="summary-value total-amount">¥{{ totalPrice.toFixed(2) }}</text>
            </view>
          </view>
        </view>
        
        <view class="modal-actions">
          <view class="cancel-btn" @click="closeCheckoutModal">
            <text class="btn-text">取消</text>
          </view>
          <view class="confirm-btn" @click="confirmCheckout" :class="{ 'loading': checkoutLoading }">
            <text class="btn-text">{{ checkoutLoading ? '处理中...' : '确认结算' }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 底部安全区域，避免内容被TabBar遮挡 -->
    <view class="tabbar-safe-area"></view>
    
    <!-- 自定义TabBar -->
    <CustomTabbar :currentPath="'pages/cart/index'" />
    </view>
  </view>
</template>

<script>
import { getUserCartList, updateCartQuantity, delCart, listCart } from '@/api/cart'
import { createOrder, getUserOrder } from '@/api/order'
import { API_CONFIG } from '@/api/config'
import cartCache from '@/utils/cartCache'
import { handleApiError, checkLoginStatus, getUserInfo } from '@/utils/loginCheck'
import { getThemeColorFromGlobal, getThemePrimaryColor } from '@/utils/themeUtils'
import PageLoading from '@/components/PageLoading/index.vue'
import pageLoadingMixin from '@/mixins/pageLoading.js'

export default {
  components: {
    PageLoading
  },
  mixins: [pageLoadingMixin],
  data() {
    return {
      isEditMode: false,
      cartItems: [],
      showCheckoutModal: false,
      checkoutLoading: false,
      themeColor: '1' // 默认主题色
    }
  },
  
  async onLoad() {
    // 开始页面加载
    this.startPageLoading()
    
    try {
      // 初始化主题色
      await this.initThemeColor()
      this.markThemeLoaded()
      
      // 加载购物车数据
      await this.loadCartData()
      
      // 标记数据已加载
      this.markDataLoaded()
    } catch (error) {
      // 购物车页面加载失败
      this.forceCompletePageLoading()
    }
  },
  
  onShow() {
    // 页面显示时重置加载状态
    this.resetPageLoadingForShow()
    
    // 页面显示时加载购物车数据
    // 检查是否需要强制刷新（从商品详情页返回时）
    const shouldRefresh = uni.getStorageSync('refreshCart')
    if (shouldRefresh) {
      // 清除刷新标记
      uni.removeStorageSync('refreshCart')
      // 清除缓存以强制从后端获取最新数据
      const userId = uni.getStorageSync('userId') || 'default'
      cartCache.clearCartCache(userId)
      // 强制刷新购物车数据
    }
    this.loadCartData()
  },
  computed: {
    // 动态主题色
    primaryColor() {
      return getThemePrimaryColor(this.themeColor)
    },
    selectedItems() {
      return this.cartItems.filter(item => item.selected)
    },
    selectedCount() {
      return this.selectedItems.reduce((total, item) => total + item.quantity, 0)
    },
    totalPrice() {
      return this.selectedItems.reduce((total, item) => total + (item.price * item.quantity), 0)
    },
    isAllSelected() {
      return this.cartItems.length > 0 && this.cartItems.every(item => item.selected)
    }
  },
  methods: {
    // 初始化主题色
    async initThemeColor() {
      try {
        // 获取主题色配置
        const themeColor = await getThemeColorFromGlobal()
        
        // 判断是否为异步主题色（数字字符串表示需要从服务器获取）
        if (/^\d+$/.test(themeColor)) {
          // 异步获取主题色
          this.themeColor = themeColor
          // 异步获取主题色
        } else {
          // 同步获取主题色（直接使用颜色值）
          this.themeColor = themeColor
          // 同步获取主题色
        }
      } catch (error) {
        // 购物车页面主题色初始化失败
        // 使用默认主题色
        this.themeColor = '1'
      }
    },
    
    async loadCartData() {
       try {
         // 获取token检查登录状态
         const token = uni.getStorageSync('App-Token')
         
         // 检查登录状态
         
         // 如果没有token，说明用户未登录
         if (!token) {
           // 用户未登录，无法加载购物车数据
           this.cartItems = []
           this.updateTabBarBadge()
           return
         }
         
         // 检查用户ID
         const storageData = uni.getStorageSync('storage_data') || {}
         const userId = storageData['user_id']
         
        // 从后端获取数据（后端会自动通过token获取当前用户ID）
        // 从后端加载购物车数据
          const response = await listCart()
         
         if (response.code === 200) {
           const cartData = response.rows || []
           
           // 检查每个购物车项的用户ID和org_id
           if (Array.isArray(cartData) && cartData.length > 0) {
             // 处理购物车数据
           }
          
          // 转换后端数据格式为前端需要的格式
          this.cartItems = cartData.map(item => {
            // 直接使用商品图片URL，不需要添加IP前缀（腾讯云COS存储）
            let imageUrl = item.productImage || ''
            
            // 处理SKU规格信息
            let spec = ''
            if (item.skuSpecInfo) {
              try {
                const specObj = JSON.parse(item.skuSpecInfo)
                spec = Object.entries(specObj).map(([key, value]) => `${key}: ${value}`).join(', ')
              } catch (e) {
                spec = item.skuSpecInfo
              }
            } else if (item.skuName) {
              spec = item.skuName
            } else {
              spec = '默认规格'
            }
            
            return {
              id: String(item.cartId), // 确保cartId作为字符串处理
              productId: item.productId,
              skuId: item.skuId,
              name: item.productName || '商品名称',
              price: parseFloat(item.productPrice || item.price || 0),
              originalPrice: parseFloat(item.originalPrice || 0),
              image: imageUrl,
              style: item.skuName || '默认',
              spec: spec,
              category: item.categoryName || '',
              quantity: parseInt(item.quantity || 1),
              stock: parseInt(item.stock || 999),
              selected: item.checked === 'Y' || item.checked === '1' || item.checked === 1
            }
          })
          
          // 后端返回的购物车数据处理完成
        } else {
          this.cartItems = []
        }
        
        // 更新tabbar角标
        this.updateTabBarBadge()
      } catch (error) {
        await handleApiError(error)
        // 发生错误时尝试从本地存储加载
        const localData = uni.getStorageSync('cartList') || []
        this.cartItems = localData
        this.updateTabBarBadge()
      }
    },
    
    saveCartData() {
       // 保存购物车数据到本地存储和缓存
       const userId = uni.getStorageSync('userId') || 'default'
       const cacheData = this.cartItems.map(item => ({
         cartId: item.id,
         productId: item.productId, // 保存商品ID
         skuId: item.skuId, // 保存SKU ID
         productName: item.name,
         productPrice: item.price,
         productImage: item.image,
         skuName: item.style,
         quantity: item.quantity,
         stock: item.stock,
         checked: item.selected ? 'Y' : 'N'
       }))
       uni.setStorageSync('cartList', this.cartItems)
       cartCache.setCartCache(userId, cacheData)
       // 更新tabbar角标
       this.updateTabBarBadge()
     },
    
    toggleEditMode() {
      this.isEditMode = !this.isEditMode
    },
    toggleItemSelect(index) {
      this.cartItems[index].selected = !this.cartItems[index].selected
      this.saveCartData()
    },
    toggleSelectAll() {
      const allSelected = this.isAllSelected
      this.cartItems.forEach(item => {
        item.selected = !allSelected
      })
      this.saveCartData()
    },
    async decreaseQuantity(index) {
      // 点击减号按钮
      if (this.cartItems[index].quantity > 1) {
        const newQuantity = this.cartItems[index].quantity - 1
        // 准备减少数量
        await this.updateItemQuantity(index, newQuantity)
      } else {
        // 数量已经是1，无法继续减少
      }
    },
    async increaseQuantity(index) {
      // 点击加号按钮
      if (this.cartItems[index].quantity < this.cartItems[index].stock) {
        const newQuantity = this.cartItems[index].quantity + 1
        // 准备增加数量
        await this.updateItemQuantity(index, newQuantity)
      } else {
        // 数量已达到库存上限，无法继续增加
      }
    },
    async updateItemQuantity(index, newQuantity) {
      try {
        // 开始更新购物车数量
        
        // 获取用户ID
        const loginResult = await checkLoginStatus()
        if (!loginResult.isLoggedIn) {
          // 用户未登录，停止更新
          return
        }
        const userId = loginResult.userId
        // 获取用户ID
        
        const item = this.cartItems[index]
        // 购物车商品信息
        
        const response = await updateCartQuantity(item.id, newQuantity, userId)
        // API响应
        
        if (response.code === 200) {
          // 数量更新成功
          this.cartItems[index].quantity = newQuantity
          this.saveCartData()
        } else {
          // 数量更新失败
          this.$modal.showToast(response.msg || '更新数量失败')
        }
      } catch (error) {
        // 更新购物车数量失败
        await handleApiError(error)
        this.$modal.showToast('更新数量失败，请重试')
      }
    },
    deleteItem(index) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这件商品吗？',
        success: async (res) => {
          if (res.confirm) {
            await this.removeCartItem(index)
          }
        }
      })
    },
    async removeCartItem(index) {
      try {
        const item = this.cartItems[index]
        const response = await delCart(item.id)
        
        if (response.code === 200) {
          this.cartItems.splice(index, 1)
          this.saveCartData()
          this.updateTabBarBadge()
          this.$modal.showToast('商品已删除')
        } else {
          this.$modal.showToast(response.msg || '删除失败')
        }
      } catch (error) {
        // 删除购物车商品失败
        await handleApiError(error)
        this.$modal.showToast('删除失败，请重试')
      }
    },
    batchDelete() {
      const selectedItems = this.cartItems.filter(item => item.selected)
      if (selectedItems.length === 0) {
        this.$modal.showToast('请选择要删除的商品')
        return
      }
      
      uni.showModal({
        title: '确认删除',
        content: `确定要删除选中的${selectedItems.length}件商品吗？`,
        success: async (res) => {
          if (res.confirm) {
            await this.batchRemoveItems(selectedItems)
          }
        }
      })
    },
    async batchRemoveItems(selectedItems) {
      try {
        const cartIds = selectedItems.map(item => item.id)
        const response = await delCart(cartIds.join(','))
        
        if (response.code === 200) {
          this.cartItems = this.cartItems.filter(item => !item.selected)
          this.saveCartData()
          this.updateTabBarBadge()
          this.$modal.showToast('商品已删除')
          this.isEditMode = false
        } else {
          this.$modal.showToast(response.msg || '删除失败')
        }
      } catch (error) {
        // 批量删除购物车商品失败
        await handleApiError(error)
        this.$modal.showToast('删除失败，请重试')
      }
    },
    goToDetail(productId) {
      // 提取原始商品ID，去除_dup_后缀
      const originalId = this.getOriginalProductId(productId)
      uni.navigateTo({
        url: `/pages/product/detail?id=${originalId}`
      })
    },
    
    // 获取原始商品ID，去除_dup_后缀
    getOriginalProductId(id) {
      if (!id) return 1
      // 如果ID包含_dup_，提取原始ID
      if (typeof id === 'string' && id.includes('_dup_')) {
        return id.split('_dup_')[0]
      }
      return id
    },
    goShopping() {
      uni.switchTab({
        url: '/pages/shop/index'
      })
    },
    checkout() {
      if (this.selectedCount === 0) {
        this.$modal.showToast('请选择要结算的商品')
        return
      }
      
      // 弹出确认结算弹窗
      this.showCheckoutModal = true
    },
    
    // 关闭结算弹窗
    closeCheckoutModal() {
      this.showCheckoutModal = false
      this.checkoutLoading = false
    },
    
    // 确认结算
    async confirmCheckout() {
      if (this.checkoutLoading) return
      
      this.checkoutLoading = true
      
      try {
        // 检查登录状态
        const token = uni.getStorageSync('App-Token')
        const userId = this.$store.state.user.id || uni.getStorageSync('userId')
        
        // 购物车结算登录状态检查
        
        if (!token) {
          this.$modal.showToast('请先登录')
          uni.navigateTo({ url: '/pages/login' })
          this.checkoutLoading = false
          return
        }
        
        // 如果userId无效，提示用户登录
        if (!userId || userId === 'default' || userId === '') {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          })
          this.checkoutLoading = false
          return
        }
        
        // 构建订单商品数据
        const orderItems = this.selectedItems.map(item => ({
          productId: item.productId,
          skuId: item.skuId,
          productName: item.name,
          productPrice: item.price,
          quantity: item.quantity,
          subtotal: (item.price * item.quantity).toFixed(2)
        }))
        
        // 构建订单数据
        const orderData = {
          userId: userId,
          totalAmount: this.totalPrice.toFixed(2),
          status: 1, // 订单状态为1（待支付）
          orgId: parseInt(API_CONFIG.ORG_ID), // 添加组织ID
          items: orderItems
        }
        
        // 购物车创建订单请求数据
        
        // 调用创建订单接口
        const response = await createOrder(orderData)
        // 购物车创建订单响应
        
        if (response.code === 200 && response.data) {
          this.$modal.showToast('订单创建成功')
          
          // 删除已结算的购物车商品
          const cartIds = this.selectedItems.map(item => item.id)
          await this.removeCartItems(cartIds)
          
          // 关闭弹窗
          this.closeCheckoutModal()
          
          // 跳转到订单详情页面 - 使用订单号参数
          // 先根据订单ID获取订单详情，然后使用订单号跳转
          const orderId = response.data.orderId || response.data.id;
          if (response.data.orderNo) {
            // 如果响应中直接包含订单号，直接使用
            uni.navigateTo({
              url: `/pages/order/detail?orderNo=${response.data.orderNo}`
            })
          } else {
            // 如果没有订单号，根据订单ID获取订单详情
            try {
              const userInfo = await getUserInfo();
              const orderDetailResponse = await getUserOrder(orderId, userInfo.userId);
              if (orderDetailResponse.code === 200 && orderDetailResponse.data && orderDetailResponse.data.orderNo) {
                uni.navigateTo({
                  url: `/pages/order/detail?orderNo=${orderDetailResponse.data.orderNo}`
                })
              } else {
                this.$modal.showToast('获取订单信息失败')
              }
            } catch (error) {
              console.error('获取订单详情失败:', error);
              this.$modal.showToast('跳转失败，请重试')
            }
          }
        } else {
          this.$modal.showToast(response.msg || '订单创建失败')
        }
      } catch (error) {
        // 购物车创建订单失败
        await handleApiError(error)
        this.$modal.showToast('订单创建失败，请重试')
      } finally {
        this.checkoutLoading = false
      }
    },
    
    // 删除购物车商品
    async removeCartItems(cartIds) {
      try {
        for (const cartId of cartIds) {
          await delCart(cartId)
        }
        // 重新加载购物车数据
        await this.loadCartData()
      } catch (error) {
        // 删除购物车商品失败
      }
    },

      

      
      // 更新tabbar购物车角标
      updateTabBarBadge() {
        try {
          const totalCount = this.cartItems.reduce((total, item) => total + parseInt(item.quantity || 0), 0)
          if (totalCount > 0) {
            uni.setTabBarBadge({
              index: 2, // 购物车tab的索引
              text: totalCount.toString()
            })
          } else {
            uni.removeTabBarBadge({
              index: 2
            })
          }
          // 购物车页面更新tabbar角标
        } catch (error) {
          // 更新tabbar角标失败
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
/* 页面动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideInUp {
  from {
    transform: translateY(30rpx);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

/* 头部样式 */
.cart-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  background: #FFFFFF;
  box-shadow: 0 2rpx 16rpx rgba(0, 0, 0, 0.06);
  
  .header-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #1A1A1A;
  }
  
  .header-actions {
    display: flex;
    align-items: center;
    gap: 15rpx;
  }
  

  
  .header-edit {
    padding: 12rpx 24rpx;
    background: var(--primary-color);
    color: #fff;
    border-radius: 20rpx;
    font-size: 26rpx;
    font-weight: 500;
    transition: all 0.3s ease;
    cursor: pointer;
    border: 1px solid var(--primary-color);
    
    &:hover {
      background: color-mix(in srgb, var(--primary-color) 80%, black 20%);
      transform: translateY(-2rpx);
      box-shadow: 0 6rpx 20rpx color-mix(in srgb, var(--primary-color) 30%, transparent 70%);
    }
    
    &:active {
      transform: translateY(0);
    }
  }
}

.cart-page {
  min-height: 100vh;
  background: linear-gradient(180deg, #F8FAFE 0%, #F2F6FC 100%);
  padding-bottom: 320rpx; /* 增加底部间距，避免被tabbar和结算栏遮挡 */
  animation: fadeIn 0.5s ease-out;
}

/* 空购物车状态 */
.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60vh;
  padding: 60rpx 40rpx;
  
  .empty-content {
    text-align: center;
    margin-bottom: 60rpx;
    
    .empty-text {
      display: block;
      font-size: 36rpx;
      color: #666;
      font-weight: 600;
      margin-bottom: 20rpx;
      line-height: 1.4;
    }
    
    .empty-desc {
      display: block;
      font-size: 26rpx;
      color: #999;
      line-height: 1.5;
    }
  }
  
  .go-shopping-btn {
    padding: 24rpx 48rpx;
    background: var(--primary-color);
    color: #fff;
    border-radius: 50rpx;
    font-size: 28rpx;
    font-weight: 600;
    transition: all 0.3s ease;
    box-shadow: 0 4rpx 20rpx color-mix(in srgb, var(--primary-color) 20%, transparent 80%);
    
    &:hover {
      transform: translateY(-4rpx);
      background: color-mix(in srgb, var(--primary-color) 80%, black 20%);
      box-shadow: 0 8rpx 30rpx color-mix(in srgb, var(--primary-color) 40%, transparent 60%);
    }
    
    &:active {
      transform: translateY(-2rpx);
    }
    
    .btn-text {
      font-weight: 600;
    }
  }
}

/* 购物车商品列表 */
.cart-item {
  background: #FFFFFF;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
  animation: slideInUp 0.5s ease-out;
  border: 1px solid color-mix(in srgb, var(--primary-color) 10%, transparent 90%);
  
  &:hover {
    transform: translateY(-2rpx);
    box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.08);
    border-color: color-mix(in srgb, var(--primary-color) 20%, transparent 80%);
  }
  
  .item-checkbox {
    margin-left: 25rpx;
    margin-right: 15rpx;
    
    .checkbox-icon {
      width: 36rpx;
      height: 36rpx;
      border: 2px solid #E5E7EB;
      border-radius: 8rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s ease;
      cursor: pointer;
      font-size: 20rpx;
      color: #FFFFFF;
      background: #FFFFFF;
      
      &:hover {
        border-color: var(--primary-color);
        transform: scale(1.05);
      }
      
      &:active {
        transform: scale(0.95);
      }
    }
    
    &.selected .checkbox-icon {
      background: var(--primary-color);
      border-color: var(--primary-color);
      animation: checkboxPulse 0.3s ease;
    }
  }
  
  @keyframes checkboxPulse {
    0% {
      transform: scale(1);
    }
    50% {
      transform: scale(1.1);
    }
    100% {
      transform: scale(1);
    }
  }
  
  .item-image {
    width: 100rpx;
    height: 100rpx;
    border-radius: 16rpx;
    overflow: hidden;
    margin-right: 15rpx;
    transition: all 0.3s ease;
    cursor: pointer;
    flex-shrink: 0;
    
    &:hover {
      transform: scale(1.05);
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
    }
    
    image {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform 0.3s ease;
    }
    
    &:hover image {
      transform: scale(1.1);
    }
  }
  
  .item-info {
    flex: 1;
    margin-right: 15rpx;
    min-width: 0;
    
    .item-name {
      display: block;
      font-size: 26rpx;
      color: #333;
      font-weight: 500;
      margin-bottom: 8rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      line-height: 1.3;
    }
    
    .item-tags {
      margin-bottom: 12rpx;
      
      .tag-row {
        display: flex;
        align-items: center;
        margin-bottom: 6rpx;
        
        .tag-label {
          font-size: 22rpx;
          color: #666;
          flex-shrink: 0;
          margin-right: 8rpx;
        }
        
        .tag-value {
          font-size: 22rpx;
          color: #999;
          background: #f5f5f5;
          padding: 4rpx 12rpx;
          border-radius: 12rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          max-width: 200rpx;
          line-height: 1.2;
        }
      }
    }
    
    .item-price-row {
      display: flex;
      align-items: center;
      gap: 8rpx;
      
      .item-price {
        font-size: 26rpx;
        color: #ff6b35;
        font-weight: 600;
      }
      
      .item-original-price {
        font-size: 20rpx;
        color: #999;
        text-decoration: line-through;
      }
    }
  }
  
  .item-actions {
    display: flex;
    align-items: center;
    gap: 12rpx;
    
    .quantity-control {
      display: flex;
      align-items: center;
      border: 1px solid #e0e0e0;
      border-radius: 8rpx;
      overflow: hidden;
      background: #fff;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
      
      .quantity-btn {
        width: 50rpx;
        height: 50rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #FFFFFF;
        border: 1px solid #E5E7EB;
        transition: all 0.3s ease;
        cursor: pointer;
        
        &:first-child {
          border-right: 1px solid #E5E7EB;
          border-radius: 8rpx 0 0 8rpx;
        }
        
        &:last-child {
          border-left: 1px solid #E5E7EB;
          border-radius: 0 8rpx 8rpx 0;
        }
        
        &:hover {
          background: #4A90E2;
          border-color: #4A90E2;
          
          .btn-text {
            color: #FFFFFF;
          }
        }
        
        &:active {
          transform: scale(0.95);
        }
        
        .btn-text {
          font-size: 28rpx;
          color: #6B7280;
          font-weight: 600;
          transition: color 0.3s ease;
        }
      }
      
      .quantity-text {
        width: 44rpx;
        text-align: center;
        font-size: 20rpx;
        color: #333;
        font-weight: 600;
        background: #fff;
        line-height: 36rpx;
      }
    }
    
    .delete-btn {
      padding: 8rpx 16rpx;
      background: #ff4757;
      border-radius: 4rpx;
      transition: all 0.3s ease;
      cursor: pointer;
      
      &:hover {
        background: #ff3742;
        transform: scale(1.05);
        box-shadow: 0 4rpx 12rpx rgba(255, 71, 87, 0.3);
      }
      
      &:active {
        transform: scale(0.95);
      }
      
      .delete-text {
        font-size: 20rpx;
        color: #fff;
        font-weight: 500;
      }
    }
  }
}

/* 底部结算栏 */
.cart-footer {
  position: fixed;
  bottom: 160rpx; /* 增加底部间距，避免被tabbar遮挡 */
  left: 0;
  right: 0;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10rpx);
  border-top: 1px solid #f0f0f0;
  padding: 25rpx 30rpx;
  padding-bottom: calc(25rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(25rpx + env(safe-area-inset-bottom));
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
  animation: slideInUp 0.5s ease-out;
  
  .footer-left {
    display: flex;
    align-items: center;
    flex: 1;
    
    .select-all {
      display: flex;
      align-items: center;
      margin-right: 30rpx;
      
      .checkbox-icon {
        width: 36rpx;
        height: 36rpx;
        border: 2px solid #E5E7EB;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15rpx;
        transition: all 0.3s ease;
        cursor: pointer;
        background: #FFFFFF;
        font-size: 20rpx;
        color: #FFFFFF;
        
        &:hover {
          border-color: var(--primary-color);
          transform: scale(1.05);
        }
        
        &:active {
          transform: scale(0.95);
        }
        
        &.selected {
        background: var(--primary-color);
        border-color: var(--primary-color);
        animation: checkboxPulse 0.3s ease;
      }
      }
      
      .select-text {
        font-size: 26rpx;
        color: #333;
      }
    }
    
    .total-info {
      flex: 1;
      
      .total-label {
        font-size: 24rpx;
        color: #666;
      }
      
      .total-price {
        font-size: 32rpx;
        color: var(--primary-color);
        font-weight: 600;
        margin-left: 10rpx;
      }
      
      .total-desc {
        font-size: 20rpx;
        color: #999;
        margin-top: 5rpx;
      }
    }
  }
  
  .footer-right {
    .checkout-btn, .batch-delete-btn {
      padding: 20rpx 30rpx;
      border-radius: 50rpx;
      font-size: 28rpx;
      font-weight: 500;
      transition: all 0.3s ease;
      cursor: pointer;
      
      &:hover {
        transform: translateY(-2rpx);
      }
      
      &:active {
        transform: translateY(0);
      }
    }
    
    .checkout-btn {
      background: var(--primary-color);
      color: #fff;
      
      &:hover {
        background: color-mix(in srgb, var(--primary-color) 80%, black 20%);
        box-shadow: 0 8rpx 25rpx color-mix(in srgb, var(--primary-color) 30%, transparent 70%);
      }
    }
    
    .batch-delete-btn {
      background: #EF4444;
      color: #FFFFFF;
      
      &:hover {
        background: #DC2626;
        box-shadow: 0 8rpx 25rpx rgba(239, 68, 68, 0.3);
      }
    }
  }
}

.quantity-text {
  font-size: 26rpx;
  color: #333;
  margin: 0 20rpx;
}

.delete-btn {
  margin-left: 20rpx;
  padding: 10rpx 20rpx;
  background: #EF4444;
  color: #FFFFFF;
  border-radius: 8rpx;
  font-size: 24rpx;
  transition: all 0.3s ease;
  
  &:hover {
    background: #DC2626;
    transform: translateY(-1rpx);
    box-shadow: 0 4rpx 12rpx rgba(239, 68, 68, 0.3);
  }
  
  &:active {
    transform: scale(0.95);
  }
  
  .delete-text {
    font-size: 24rpx;
    color: #FFFFFF;
    font-weight: 500;
  }
}

/* 确认结算弹窗样式 */
.checkout-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  width: 90%;
  max-width: 600rpx;
  background: #FFFFFF;
  border-radius: 20rpx;
  overflow: hidden;
  animation: modalSlideUp 0.3s ease-out;
}

@keyframes modalSlideUp {
  from {
    transform: translateY(100rpx);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;
  border-bottom: 1rpx solid #F5F7FA;
}

.modal-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #1A1A1A;
}

.close-btn {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  background: #F5F7FA;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  
  &:active {
    background: #E8F2FF;
    transform: scale(0.9);
  }
}

.close-icon {
  font-size: 40rpx;
  color: #8B9BB0;
  font-weight: 300;
}

.modal-body {
  padding: 32rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.order-summary {
  margin-bottom: 32rpx;
}

.summary-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #1A1A1A;
  margin-bottom: 24rpx;
  display: block;
}

.goods-list {
  max-height: 300rpx;
  overflow-y: auto;
}

.goods-item {
  display: flex;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #F5F7FA;
  
  &:last-child {
    border-bottom: none;
  }
}

.goods-image {
  width: 80rpx;
  height: 80rpx;
  border-radius: 12rpx;
  margin-right: 16rpx;
}

.goods-info {
  flex: 1;
}

.goods-name {
  font-size: 28rpx;
  color: #1A1A1A;
  font-weight: 500;
  display: block;
  margin-bottom: 8rpx;
}

.goods-spec {
  font-size: 24rpx;
  color: #8B9BB0;
  display: block;
  margin-bottom: 8rpx;
}

.goods-price-qty {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.goods-price {
  font-size: 28rpx;
  color: #FF6B35;
  font-weight: 600;
}

.goods-qty {
  font-size: 24rpx;
  color: #8B9BB0;
}

.payment-summary {
  border-top: 1rpx solid #F5F7FA;
  padding-top: 24rpx;
}

.summary-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16rpx;
  
  &.total-row {
    margin-bottom: 0;
    padding-top: 16rpx;
    border-top: 1rpx solid #F5F7FA;
  }
}

.summary-label {
  font-size: 28rpx;
  color: #1A1A1A;
}

.summary-value {
  font-size: 28rpx;
  color: #1A1A1A;
  font-weight: 500;
  
  &.total-amount {
    font-size: 32rpx;
    color: #FF6B35;
    font-weight: 600;
  }
}

.modal-actions {
  display: flex;
  padding: 24rpx 32rpx 32rpx;
  gap: 24rpx;
}

.cancel-btn, .confirm-btn {
  flex: 1;
  height: 88rpx;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.cancel-btn {
  background: #F5F7FA;
  border: 1rpx solid #E5E7EB;
  
  &:active {
    background: #E5E7EB;
    transform: scale(0.98);
  }
  
  .btn-text {
    font-size: 32rpx;
    color: #6B7280;
    font-weight: 500;
  }
}

.confirm-btn {
  background: var(--primary-color);
  box-shadow: 0 8rpx 24rpx color-mix(in srgb, var(--primary-color) 30%, transparent 70%);
  
  &:hover {
    background: color-mix(in srgb, var(--primary-color) 80%, black 20%);
    box-shadow: 0 8rpx 25rpx color-mix(in srgb, var(--primary-color) 30%, transparent 70%);
  }
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 12rpx color-mix(in srgb, var(--primary-color) 40%, transparent 60%);
  }
  
  &.loading {
    opacity: 0.7;
    pointer-events: none;
  }
  
  .btn-text {
    font-size: 32rpx;
    color: #FFFFFF;
    font-weight: 600;
  }
}

/* TabBar安全区域 */
.tabbar-safe-area {
  height: 200rpx;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}
</style>
